package com.edmendst.xmall.service.impl;


import com.edmendst.xmall.dto.AdminRegisterAndLogin;
import com.edmendst.xmall.dto.ProductCategory;
import com.edmendst.xmall.mapper.AdminMapper;
import com.edmendst.xmall.mapper.CategoryMapper;
import com.edmendst.xmall.pojo.Admin;
import com.edmendst.xmall.pojo.AdminExample;
import com.edmendst.xmall.pojo.Category;
import com.edmendst.xmall.pojo.CategoryExample;
import com.edmendst.xmall.security.PasswordSecurity;
import com.edmendst.xmall.service.AdminService;
import com.edmendst.xmall.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private AdminMapper adminMapper;

    //管理员注册
    @Override
    public String register(AdminRegisterAndLogin adminRegisterandlogin) {

        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andAdminNameEqualTo(adminRegisterandlogin.getAdminName());
        List<Admin> adminList = adminMapper.selectByExample(adminExample);

        if (!adminList.isEmpty()){
            return "管理员已存在";
        }

        Admin admin = new Admin();
        PasswordSecurity passwordSecurity = new PasswordSecurity();
        admin.setAdminName(adminRegisterandlogin.getAdminName());
        String encodedPassword = passwordSecurity.encodePassword(adminRegisterandlogin.getAdminPassword());
        admin.setAdminPassword(encodedPassword);
        admin.setAdminPermissionLevel((byte) 1);
        adminMapper.insert(admin);
        return "注册成功";
    }

    //管理员登录
    @Override
    public String login(AdminRegisterAndLogin adminRegisterandlogin) {
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andAdminNameEqualTo(adminRegisterandlogin.getAdminName());
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        if (adminList.size()==1){
            Admin admin = adminList.get(0);
            PasswordSecurity passwordSecurity = new PasswordSecurity();
            boolean b = passwordSecurity.matchPassword(adminRegisterandlogin.getAdminPassword(), admin.getAdminPassword());
            if (b){
                String generateToken = jwtUtil.generateToken(adminRegisterandlogin.getAdminName(),"ROLE_ADMIN");
                return StringUtils.hasText(generateToken) ? generateToken : "令牌生成失败";
            }else {
                return "密码错误";
            }
        }
        return "验证成功";
    }




}
